//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using OpenLS.Spreadsheet.Expressions;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Parsing
{
    internal class ExternalNameExpression : Expression
    {
        private readonly Workbook _workbook;
        private readonly ExternalWorkbook _book;
        private readonly string _name;
        private readonly List<Expression> _parameters;
        public override IEnumerable<Expression> GetSubExpressions()
        {
            yield break;
        }
        public ExternalNameExpression(Workbook workbook, ExternalWorkbook book, string name, List<Expression> parameters)
        {
            Contract.Requires(book != null);
            Contract.Requires(name != null);
            _workbook = workbook;
            _book = book;
            _name = name;
            _parameters = parameters;
        }
        internal override Expression Transposed(Cell target)
        {
            return this;
        }

        public override string GetText(TextContext context)
        {
            int index = 0;
            foreach (var list in _workbook.ExternalLinks)
            {
                if (list.ExternalBook == _book)
                    break;
                index++;
            }
            string result =  "[" + index + "]" + _name;
            if (_parameters != null)
            {
                result += "(";
                if (_parameters.Count > 0)
                {
                    var last = _parameters[_parameters.Count - 1];
                    foreach (var expression in _parameters)
                    {
                        result += expression.GetText(context);
                        if (expression != last)
                            result += ",";

                    }
                }
                result += ")";
            }
            return result;
        } 

        public override IEnumerable<IDependencyNode> GetPrecedents(EvaluationContext context)
        {
            yield break;
        }

        protected override object GetObjectImp(EvaluationContext context)
        {
            return null;
        }

        public override Expression Offset(CellRelativeAddress a)
        {
            return this;
        }
    }
}